<template>
  <div class="chat-container">
    <!-- 头部 -->
    <div class="chat-header">
      <div class="header-left">
        <h3>在线客服聊天</h3>
        <span class="connection-status" :class="{ connected: connected }">
          {{ connected ? '已连接' : '连接中...' }}
        </span>
      </div>
      <div class="header-right">
        <span class="user-info">
          欢迎，{{ user.nickname || user.username }}
          <el-tag :type="getUserTypeTag(userType)" size="mini">
            {{ getUserTypeText(userType) }}
          </el-tag>
        </span>
        <el-button type="text" @click="logout">退出</el-button>
      </div>
    </div>

    <div class="chat-main">
      <!-- 左侧用户列表 -->
      <div class="user-list">
        <div class="list-header">
          <h4>在线用户 ({{ onlineUsers.length }})</h4>
        </div>
        <div class="user-items">
          <div
            v-for="user in onlineUsers"
            :key="user.id"
            class="user-item"
            :class="{ active: currentReceiver && currentReceiver.id === user.id }"
            @click="selectUser(user)"
          >
            <div class="user-avatar">
              <i class="el-icon-user"></i>
            </div>
            <div class="user-info">
              <div class="user-name">{{ user.nickname || user.username }}</div>
              <div class="user-type">{{ getUserTypeText(user.userType) }}</div>
            </div>
            <div class="online-indicator"></div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <!-- 聊天消息 -->
        <div class="message-list" ref="messageList">
          <div
            v-for="message in messages"
            :key="message.id"
            class="message-item"
            :class="{ 'own-message': message.senderId === user.id }"
          >
            <div class="message-avatar">
              <i class="el-icon-user"></i>
            </div>
            <div class="message-content">
              <div class="message-header">
                <span class="sender-name">{{ getSenderName(message.senderId) }}</span>
                <span class="message-time">{{ formatTime(message.createTime) }}</span>
              </div>
              <div class="message-body">
                <div v-if="message.messageType === 'text'" class="text-message">
                  {{ message.content }}
                </div>
                <div v-else-if="message.messageType === 'order'" class="order-message">
                  <el-card class="order-card">
                    <div slot="header">
                      <span>订单信息</span>
                    </div>
                    <div class="order-content">
                      <p><strong>订单号：</strong>{{ message.content }}</p>
                      <p><strong>状态：</strong>待处理</p>
                    </div>
                  </el-card>
                </div>
                <div v-else-if="message.messageType === 'system'" class="system-message">
                  <i class="el-icon-info"></i>
                  {{ message.content }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-toolbar">
            <el-button-group>
              <el-button size="mini" @click="sendCommand('QUERY_ORDER')">查询订单</el-button>
              <el-button size="mini" @click="sendCommand('APPLY_REFUND')">申请退款</el-button>
            </el-button-group>
          </div>
          <div class="input-box">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="请输入消息内容..."
              @keyup.enter.native="sendTextMessage"
            ></el-input>
            <el-button
              type="primary"
              :disabled="!inputMessage.trim() || !currentReceiver"
              @click="sendTextMessage"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import { getChatHistory, getOnlineUsers } from '@/api/chat'
import WebSocketClient from '@/utils/websocket'
import dayjs from 'dayjs'

export default {
  name: 'Chat',
  data() {
    return {
      inputMessage: '',
      onlineUsers: [],
      messages: [],
      currentReceiver: null,
      websocket: null,
      connected: false
    }
  },
  computed: {
    // 合并所有计算属性到一个 computed 块中
    ...mapGetters(['userType', 'token']),
    ...mapState({
      user: state => state.user || {}
    }),
    // 添加用户显示名称的计算属性
    userDisplayName() {
      return this.user?.nickname || this.user?.username || '用户'
    }
  },
  mounted() {
    // 确保有 token 再初始化连接
    if (this.token) {
      this.initWebSocket()
      this.loadOnlineUsers()
    } else {
      console.warn('没有 token，无法初始化 WebSocket')
      // 可以考虑重定向到登录页
      this.$router.push('/login')
    }
  },
  beforeDestroy() {
    if (this.websocket) {
      this.websocket.close()
    }
  },
  methods: {
    // 初始化WebSocket连接
    initWebSocket() {
      this.websocket = new WebSocketClient()
      
      this.websocket.on('connected', () => {
        this.connected = true
        this.$message.success('连接成功')
      })
      
      this.websocket.on('disconnected', () => {
        this.connected = false
        this.$message.warning('连接断开')
      })
      
      this.websocket.on('message', (data) => {
        this.handleWebSocketMessage(data)
      })
      
      this.websocket.on('error', (error) => {
        console.error('WebSocket错误:', error)
        this.$message.error('连接错误')
        // 如果 token 无效，重定向到登录页
        if (error.message && error.message.includes('auth')) {
          this.$router.push('/login')
        }
      })
      
      this.websocket.connect(this.token)
    },

    // 处理WebSocket消息
    handleWebSocketMessage(data) {
      if (data.type === 'chat' || data.type === 'push') {
        this.messages.push(data)
        this.scrollToBottom()
      } else if (data.type === 'system') {
        this.$message.info(data.content)
      } else if (data.type === 'error') {
        this.$message.error(data.content)
      } else if (data.type === 'online_users') {
        // 处理在线用户更新
        this.onlineUsers = data.users || []
      }
    },

    // 加载在线用户
    async loadOnlineUsers() {
      try {
        // 确保有 token 再请求
        if (!this.token) {
          console.warn('没有 token，无法加载在线用户')
          return
        }
        
        const response = await getOnlineUsers()
        this.onlineUsers = response.data.onlineUsers || []
      } catch (error) {
        console.error('加载在线用户失败:', error)
        // 如果 token 无效，重定向到登录页
        if (error.response && error.response.status === 401) {
          this.$router.push('/login')
        }
      }
    },

    // 选择用户
    selectUser(user) {
      this.currentReceiver = user
      this.loadChatHistory(user.id)
    },

    // 加载聊天历史
    async loadChatHistory(receiverId) {
      try {
        const response = await getChatHistory({ receiverId })
        this.messages = response.data || []
        this.scrollToBottom()
      } catch (error) {
        console.error('加载聊天历史失败:', error)
      }
    },

    // 发送文本消息
    sendTextMessage() {
      if (!this.inputMessage.trim() || !this.currentReceiver) {
        return
      }

      const message = {
        messageType: 'text',
        content: this.inputMessage.trim(),
        receiverId: this.currentReceiver.id,
        senderId: this.user.id // 添加发送者ID
      }

      this.websocket.send(message)
      this.inputMessage = ''
    },

    // 发送指令
    sendCommand(commandType) {
      if (!this.currentReceiver) {
        this.$message.warning('请先选择聊天对象')
        return
      }

      const message = {
        messageType: 'command',
        content: `执行指令: ${commandType}`,
        receiverId: this.currentReceiver.id,
        senderId: this.user.id, // 添加发送者ID
        commandType: commandType,
        commandParams: JSON.stringify({ timestamp: Date.now() })
      }

      this.websocket.send(message)
    },

    // 获取发送者姓名
    getSenderName(senderId) {
      if (senderId === this.user.id) {
        return '我'
      }
      const sender = this.onlineUsers.find(u => u.id === senderId)
      return sender ? (sender.nickname || sender.username) : '未知用户'
    },

    // 获取用户类型标签
    getUserTypeTag(userType) {
      switch (userType) {
        case 1: return 'info'
        case 2: return 'warning'
        case 3: return 'danger'
        default: return 'info'
      }
    },

    // 获取用户类型文本
    getUserTypeText(userType) {
      switch (userType) {
        case 1: return '用户'
        case 2: return '客服'
        case 3: return '管理员'
        default: return '用户'
      }
    },

    // 格式化时间
    formatTime(time) {
      return dayjs(time).format('HH:mm:ss')
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const messageList = this.$refs.messageList
        if (messageList) {
          messageList.scrollTop = messageList.scrollHeight
        }
      })
    },

    // 退出登录
    logout() {
      this.$confirm('确认退出登录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 根据您的 Vuex 结构调整 action 路径
        this.$store.dispatch('logout').then(() => {
          this.$router.push('/login')
        }).catch(error => {
          console.error('退出登录失败:', error)
          // 即使退出失败也重定向到登录页
          this.$router.push('/login')
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;

  .chat-header {
    height: 60px;
    background: white;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .header-left {
      display: flex;
      align-items: center;

      h3 {
        margin: 0 15px 0 0;
        color: #333;
      }

      .connection-status {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        background: #f56c6c;
        color: white;

        &.connected {
          background: #67c23a;
        }
      }
    }

    .header-right {
      display: flex;
      align-items: center;

      .user-info {
        margin-right: 15px;
        color: #666;
      }
    }
  }

  .chat-main {
    flex: 1;
    display: flex;
    overflow: hidden;

    .user-list {
      width: 250px;
      background: white;
      border-right: 1px solid #e6e6e6;
      display: flex;
      flex-direction: column;

      .list-header {
        padding: 15px;
        border-bottom: 1px solid #e6e6e6;

        h4 {
          margin: 0;
          color: #333;
        }
      }

      .user-items {
        flex: 1;
        overflow-y: auto;

        .user-item {
          padding: 15px;
          border-bottom: 1px solid #f0f0f0;
          cursor: pointer;
          display: flex;
          align-items: center;
          transition: background-color 0.3s;

          &:hover {
            background: #f5f5f5;
          }

          &.active {
            background: #e6f7ff;
            border-left: 3px solid #1890ff;
          }

          .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            color: #999;
          }

          .user-info {
            flex: 1;

            .user-name {
              font-weight: 500;
              color: #333;
              margin-bottom: 2px;
            }

            .user-type {
              font-size: 12px;
              color: #999;
            }
          }

          .online-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #67c23a;
          }
        }
      }
    }

    .chat-area {
      flex: 1;
      display: flex;
      flex-direction: column;

      .message-list {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
        background: #fafafa;

        .message-item {
          display: flex;
          margin-bottom: 20px;

          &.own-message {
            flex-direction: row-reverse;

            .message-content {
              background: #1890ff;
              color: white;

              .message-header {
                color: rgba(255, 255, 255, 0.8);
              }
            }
          }

          .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 10px;
            color: #999;
          }

          .message-content {
            max-width: 60%;
            background: white;
            border-radius: 8px;
            padding: 10px 15px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

            .message-header {
              display: flex;
              justify-content: space-between;
              margin-bottom: 5px;
              font-size: 12px;
              color: #999;

              .sender-name {
                font-weight: 500;
              }
            }

            .message-body {
              .text-message {
                line-height: 1.5;
              }

              .order-message {
                .order-card {
                  margin: 0;
                  border: none;
                  box-shadow: none;
                }
              }

              .system-message {
                color: #666;
                font-style: italic;

                i {
                  margin-right: 5px;
                }
              }
            }
          }
        }
      }

      .input-area {
        background: white;
        border-top: 1px solid #e6e6e6;
        padding: 15px;

        .input-toolbar {
          margin-bottom: 10px;
        }

        .input-box {
          display: flex;
          align-items: flex-end;

          .el-textarea {
            flex: 1;
            margin-right: 10px;
          }
        }
      }
    }
  }
}
</style>
